const axios = require('../utils/axios');
const PushMsgURL = 'https://ld.fddzsteel.com:30809/madp-app/ms/push/pushMsg';
const xshURL = 'http://10.1.128.16:8081/api/v1/loginstatus/getNotLoginUserList';


exports.PushMsgToLeader = async (req, res) => {
   try {
      const response1 = await axios.get(xshURL);
      if (response1.status != "succeed") {
         res.json({
            code: 200,
            msg: '调用128.16接口返回失败信息:' + response1.status,
            data: null
         })
         return;
      }
      // 验证响应中是否包含所需数据
      if (response1.uid.length == 0) {
         res.json({
            code: 200,
            msg: '所有用户都已登录'
         })
         return;
      }

      // 提取用户ID列表
      let userList = response1.uid;
      let unameList = response1.uname;
      // console.log("userlist:", userList);
      // console.log(`获取到 ${userList.length} 个用户数据`);
      // 第二步：遍历每个用户ID，单独发送消息
      const results = [];
      const errors = [];
      if (req.body.runMode == 'test') {
         userList = ['11021', '11713'];
      }
      for (const user of userList) {
         try {
            const userId = user;
            // 为每个用户创建单独的请求参数
            const par2 = {
               data: {
                  param_0: {
                     msgSid: "141",
                     sender: "系统管理员",
                     taskId: "DSJZX0001",
                     loginIds: [userId], // 每个请求只包含一个用户ID
                     transmission: {
                        title: "中高层未登录提醒",
                        content: "您今日在工业互联网平台中的大数据或智灵动APP中的大数据登录次数为零，请尽快完成系统登录！",
                        appletId: "DSJZX0001_001",
                        btnTxt: "查看详情"
                     }
                  }
               }
            };
            // console.log(`向用户 ${userId} 发送消息...`);
            const response2 = await axios.post(PushMsgURL, par2);
            results.push({
               userId,
               response: response2.msg
            });
            // console.log(`向用户 ${userId} 发送消息成功`);
            // 可选：添加延迟，避免请求过于频繁
            // await new Promise(resolve => setTimeout(resolve, 100)); // 100ms延迟

         } catch (pushError) {
            console.error(`向用户发送消息失败:`, pushError);
            errors.push({
               userId: user.uid || 'unknown',
               error: pushError.message || String(pushError)
            });
         }
      }
      // 第三步：返回处理结果
      return res.status(200).json({
         success: true,
         message: `消息推送完成，成功 ${results.length} 条，失败 ${errors.length} 条`,
         data: {
            total: userList.length,
            successCount: results.length,
            errorCount: errors.length,
            results,
            unameList
         }
      });
   } catch (error) {
      console.error('推送消息流程失败:', error);
      return res.status(500).json({
         success: false,
         message: '推送消息失败',
         error: error.message || String(error)
      });
   }
}